package zym.diandian.module.popup;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.InputDeviceCompat;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

import zym.diandian.R;

//全局背景
public class PopupFrame extends Fragment implements View.OnClickListener {
    private Button color_pick, pic_pick;
    private EditText input_color, input_alpha;
    private ColorPicker colorPicker;
    private int screenWidth, screenHeight;
    private ImageView img;
    private PopView pop;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        setHasOptionsMenu(true);
        return inflater.inflate(R.layout.popup_fragment, null);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        DisplayMetrics metrics = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);

        this.screenWidth = metrics.widthPixels;

        this.screenHeight = metrics.heightPixels;

        this.color_pick = (Button) view.findViewById(R.id.color_pick);
        this.pic_pick = (Button) view.findViewById(R.id.pic_pick);
        this.img = (ImageView) view.findViewById(R.id.img);

        this.input_color = (EditText) view.findViewById(R.id.input_color);
        this.input_alpha = (EditText) view.findViewById(R.id.input_alpha);

        color_pick.setOnClickListener(this);
        pic_pick.setOnClickListener(this);

        try {
            getActivity().getActionBar().setSubtitle("如果点击开启后无任何反应请检查程序权限");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.menu_pop, menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_pop_start:
                //开启
                String alpha = this.input_alpha.getText().toString().trim();
                String color = this.input_color.getText().toString().trim();
                String imagepath = this.img.getTag() + "";

                this.pop = new PopView(getActivity(), alpha, Integer.parseInt(color), imagepath, true, getActivity().getWindowManager(), screenWidth, screenHeight);
                this.startPop(this.pop);

                break;
            case R.id.menu_pop_stop:
                //关闭
                if (pop != null) {
                    getActivity().getWindowManager().removeView(pop);
                    pop = null;
                }
                break;
            case R.id.menu_pop_notice:
                //帮助
                break;
            default:
                break;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.color_pick:
                startColorPickerDialog(getActivity(), screenWidth, screenHeight);
                break;
            case R.id.pic_pick:
                Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(intent, 1);
                break;
            default:
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 1://图片选择
                if (resultCode == Activity.RESULT_OK) {
                    Uri uri = data.getData();
                    try {
                        String imgPath = Uri2File(getActivity(), uri);
                        Toast.makeText(getActivity(), "" + imgPath, Toast.LENGTH_SHORT).show();
                        img.setTag(imgPath);

                        InputStream is = new FileInputStream(imgPath);
                        Bitmap bitmap = BitmapFactory.decodeStream(is);
                        img.setImageBitmap(bitmap);
                        is.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                        Toast.makeText(getActivity(), "图片读取失败", Toast.LENGTH_LONG).show();
                    }
                }
                break;
        }
    }

    public static String Uri2File(Context context, Uri uri) {
        String img_path = "";
        try {
            String[] proj = {MediaStore.MediaColumns.DATA};
            Cursor actualimagecursor = context.getContentResolver().query(uri, proj, null, null, null);
            int actual_image_column_index = actualimagecursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
            actualimagecursor.moveToFirst();

            img_path = actualimagecursor.getString(actual_image_column_index);
            File file = new File(img_path);
            Uri.fromFile(file);
        } catch (Exception e) {
            e.printStackTrace();
            img_path = "N/A";
        }

        return img_path;
    }

    //打开颜色选择对话框
    private void startColorPickerDialog(Context context, int width, int height) {
        this.colorPicker = new ColorPicker(context, Color.BLACK, width, height);
        this.colorPicker.show();
        this.colorPicker.setOnDismissListener(new DialogInterface.OnDismissListener() {

            @Override
            public void onDismiss(DialogInterface dialog) {
                int color = colorPicker.getColor();
                input_color.setText(color + "");
                input_color.setTextColor(color);
            }
        });
    }

    private void startPop(@NonNull View v) {
        WindowManager.LayoutParams params = new WindowManager.LayoutParams();

        params.type = WindowManager.LayoutParams.TYPE_SYSTEM_ERROR;
        params.width = ViewGroup.LayoutParams.MATCH_PARENT;
        params.height = ViewGroup.LayoutParams.MATCH_PARENT;
        params.gravity = Gravity.TOP;
        // params.alpha = 100;
        params.format = PixelFormat.TRANSLUCENT;
        if (false) {
            //通知栏
            params.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE | WindowManager.LayoutParams.FIRST_SYSTEM_WINDOW;
        } else {
            params.flags = /* WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | */WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
        }

        getActivity().getWindowManager().addView(v, params);

        Toast.makeText(getActivity(), "如果发现某些按钮无法点击请退出当前程序", Toast.LENGTH_SHORT).show();
    }
}
